//
//  DocumentController.m
//  NVAReader
//
//  Created by DuyLK on 6/4/14.
//  Copyright (c) 2014 com.nva.nvareader. All rights reserved.
//

#import "DocumentController.h"
#include "common.h"
#include "mupdf/pdf.h"
#include <stdlib.h>
#include <unistd.h>
static void expandOutLine(NSMutableArray *rootOutline, fz_outline *outline, int level)
{
    while (outline)
	{
        if (outline->dest.kind == FZ_LINK_GOTO)
		{
            int page = outline->dest.ld.gotor.page + 1;
			if (page >= 0 && outline->title)
			{
                if(level == 0)
                {
                    NSString *pageNumber = [NSString stringWithFormat:@"%d",page];
                    NSString *title = [NSString stringWithUTF8String: outline->title];
                    OutlineItem *item = [[OutlineItem alloc] initWithTitle:title page:pageNumber];
                    [rootOutline addObject:item];
                }else
                {
                    if(level == 1)
                    {
                        NSString *pageNumber = [NSString stringWithFormat:@"%d",page];
                        NSString *title = [NSString stringWithUTF8String: outline->title];
                        OutlineItem *item = [[OutlineItem alloc] initWithTitle:title page:pageNumber];
                        [(OutlineItem*)[rootOutline objectAtIndex:[rootOutline count] - 1] addChildrenItem:item];
                    }else
                    {
                        int temp = 0;
                        OutlineItem *childleveone = (OutlineItem*)[rootOutline objectAtIndex:[rootOutline count] - 1];
                        while (temp < level - 1) {
                            childleveone = (OutlineItem*)[childleveone.childrenItem objectAtIndex:[childleveone.childrenItem count] -1];
                            temp++;
                        }
                        NSString *pageNumber = [NSString stringWithFormat:@"%d",page];
                        NSString *title = [NSString stringWithUTF8String: outline->title];
                        OutlineItem *item = [[OutlineItem alloc] initWithTitle:title page:pageNumber];
                        [childleveone addChildrenItem:item];
                    }
                }
            }
        }
        expandOutLine(rootOutline,outline->down, level + 1);
        outline = outline->next;
    }
}

static void saveDoc(char *current_path, fz_document *doc)
{
	fz_write_options opts;
	opts.do_incremental = 1;
	opts.do_ascii = 0;
	opts.do_expand = 0;
	opts.do_garbage = 0;
	opts.do_linear = 0;
    int written = 0;
    fz_try(ctx)
    {
        fz_write_document(doc, current_path, &opts);
        written  = 1;
    }fz_catch(ctx)
    {
        written = 0;
    }
}


@implementation DocumentController
@synthesize window;
- (id)init
{
    self = [super init];
    if (self) {
        queue = dispatch_queue_create("com.nva.nvareader", NULL);
        ctx = fz_new_context(NULL, NULL, 1024<<20);
        fz_register_document_handlers(ctx);
       
        currentThumbnail = -1;
        _currentZoom = 8;
    }
    return self;
}

- (NSString *)windowNibName
{
    return @"MainMenu";
}

- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"path"];
    [defaults removeObjectForKey:@"name"];
}

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
    if (outError) {
        *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:nil];
    }
    return nil;
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
    if (outError) {
        *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:nil];
    }
    return YES;
}

-(BOOL) readFromURL:(NSURL *)url ofType:(NSString *)typeName error:(NSError **)outError
{
    NSString *path = [url path];
    NSString *name = [[[url copy] path] lastPathComponent];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:path forKey:@"path"];
    [defaults setObject:name forKey:@"name"];
	return YES;
}

-(void) windowWillClose:(NSNotification *)notification
{
    NSLog(@"windows will close");
    NSWindow *windowClose = (NSWindow *)[notification object];
    if(windowClose != window)
    {
        [NSApp stopModalWithCode:0];
        int colorDraw = colorCode(_colorSetting);
        if (_typeSettingColor ==1) {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setInteger:colorDraw forKey: @"ColorHighLight"];
            [defaults synchronize];
        }else if (_typeSettingColor ==2)
        {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setInteger:colorDraw forKey: @"ColorUnderLine"];
            [defaults synchronize];
        }else if (_typeSettingColor ==3)
        {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setInteger:colorDraw forKey: @"ColorStrikeOut"];
            [defaults synchronize];
        }else if (_typeSettingColor ==4)
        {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setInteger:colorDraw forKey: @"ColorDraw"];
            [defaults synchronize];
        }
    }else
    {
        if(doc)
        {
            pdf_document *idoc = pdf_specifics(doc);
            if (idoc && pdf_has_unsaved_changes(idoc))
            {
                NSAlert *alert = [[NSAlert alloc] init];
                [alert addButtonWithTitle:@"Save Document"];
                [alert addButtonWithTitle:@"Cancel"];
                [alert setMessageText:@"Save Document?"];
                [alert setInformativeText:@"Changes have been made to the document that will be lost if not saved"];
                [alert setAlertStyle:NSWarningAlertStyle];
                if ([alert runModal] == NSAlertFirstButtonReturn) {
                    // OK clicked, delete the record
                    saveDoc(_filePath,doc);
                }else
                {
                    NSLog(@"Cancle");
                }
                [alert release];
            }
            //[super close];
            //exit(0);
            //[super updateChangeCount:NSChangeCleared];
        }
    }
}

+ (BOOL)autosavesInPlace
{
    return YES;
}


-(void) awakeFromNib
{
    self.searchField.delegate =self;
    [_searchTable setDelegate:self];
    //disable segment search
    [_segmentSearch setEnabled:NO];
    [_listView setHasHozScroll:NO];
    [_listPage setHasHozScroll:YES];
    [_searchTableView setHidden:YES];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *path = [defaults objectForKey:@"path"];
    NSString *name = [defaults objectForKey:@"name"];
    [[[_searchField cell] cancelButtonCell] setAction: @selector(clearTextSearch)];
    [[[_searchField cell] cancelButtonCell] setTarget:self];
    [self.window setDelegate:self];
    if (path && name) {
        [self openDocument:name:path];
    }
}


- (void) openDocument:(NSString *)filename :(NSString *)filePath
{
    if (filename == nil || filePath==nil) {
        return;
    }
	NSString *nspath = filePath;
	_filePath = malloc(strlen([nspath UTF8String])+1);
	if (_filePath == NULL) {
        NSRunAlertPanel(@"Error!", @"Out of memory in openDocument", @"OK", @"Cancel", nil);
		return;
	}
    
	strcpy(_filePath, [nspath UTF8String]);
    
	dispatch_sync(queue, ^{});
    
	printf("open document '%s'\n", _filePath);
    
	_filename = [filename retain];
	[docRef release];
	docRef = [[DocRef alloc] initWithFilename:_filePath];
	if (!docRef) {
        NSRunAlertPanel(@"Error!", @"Cannot open document!" , @"OK", @"Cancel", nil);
		return;
	}
    
	if (fz_needs_password(docRef->doc))
		[self askForPassword: @"'%@' needs a password:"];
	else
    {
		[self onPasswordOkay:_filename path:_filePath document:docRef];
        NSRect screenRect = [[NSScreen mainScreen] frame];
        [self.window setFrame:screenRect display:YES];
        [_toolbar setSelectedItemIdentifier: @"hand"];
        
    }
}


- (void) askForPassword: (NSString*)prompt
{
    
}


- (void) onPasswordOkay:(NSString *)filename path:(char *)cstr document:(DocRef *)aDoc
{
    doc = docRef->doc;
    dispatch_sync(queue, ^{});
	fz_outline *root = fz_load_outline(doc);
    if (root) {
        NSMutableArray *outLineRoot = [[NSMutableArray alloc] init];
        expandOutLine(outLineRoot, root, 0);
        if ([outLineRoot count] > 0) {
            OutlineViewController *outline = [[OutlineViewController alloc] initWithData:outLineRoot];
            if([outline countChild] > 0)
            {
                [_outLineView setDataSource:outline];
                if([_outLineParent isHidden])
                {
                    [_outLineParent setHidden:NO];
                }
                if(_thumbnail)
                {
                    [_thumbnail showHideThumbnails:YES];
                }
                [_segmentOutLineThumb setSelectedSegment:0];
            }else{
                [_segmentOutLineThumb setEnabled:NO forSegment:0];
                [_segmentOutLineThumb setSelectedSegment:1];
                if(![_outLineParent isHidden])
                {
                    [_outLineParent setHidden:YES];
                }
                //thumbnail
                if(_thumbnail)
                {
                    [_thumbnail showHideThumbnails:NO];
                }
            }
            //caculator size page co nhieu loai pdf no ko phai
            //kich thuoc nhu A4 => fuck
        }
        fz_free_outline(ctx, root);
    }else
    {
        [_segmentOutLineThumb setEnabled:NO forSegment:0];
        [_segmentOutLineThumb setSelectedSegment:1];
        if(![_outLineParent isHidden])
        {
            [_outLineParent setHidden:YES];
        }
        //thumbnail
        if(_thumbnail)
        {
            [_thumbnail showHideThumbnails:NO];
        }
    }
    
    if(doc)
    {
        fz_rect bounds;
        int total = fz_count_pages(doc);
        totalPage = total;
        int _number =  0;
        if(total > 1)
            _number = 1;
        page = fz_load_page(doc, _number);
        fz_bound_page(doc, page, &bounds);
        int width = bounds.x1 - bounds.x0;
        int height = bounds.y1 - bounds.y0;
        NSRect size  = [_leftControl frame];
        float scale = width/size.size.width;
        height = (int) height/scale;
        width = size.size.width/scale;
        _thumbnail = [[ThumbnailsController alloc] initWithDocument:doc :width :height];
        _thumbnail.delegate = self;
        [_listView setDelegate:_thumbnail];
        [_listView reloadData];
        
        NSRect sizeRight = [_rightControl frame];
        float scaleRight = (bounds.x1 - bounds.x0)/sizeRight.size.width;
        int withPage = (bounds.x1 - bounds.x0)/scaleRight;
        int heightPage = (bounds.y1 - bounds.y0)/scaleRight;
        _pageController = [[PageController alloc] initWithDocument:doc width:withPage height:heightPage];
        _pageController.delegate=self;
        [_listPage setDelegate:_pageController];
        [_listPage reloadData];
        
        _comboPageController = [[ComboPageController alloc] initWithNumberPage:totalPage];
        [_comboPage setDataSource:_comboPageController];
        [_comboPage selectItemAtIndex:0];
        [_comboPage reloadData];
        
        _comboZoomController = [[ComboPageController alloc] initWithZoomPage];
        [_comboZoom setDataSource:_comboZoomController];
        [_comboZoom selectItemAtIndex:9];
        [_comboZoom reloadData];
        [window setTitle:filename];
    }
}


- (void) onPasswordCancel
{
    
}

- (void) reload
{
    
}

#pragma event

///event when click next page
- (IBAction)nextPage:(id)sender {
    int currentPage = [_pageController currentPage];
    if(currentPage + 1 < totalPage)
    {
        [_pageController setCurrentPage:currentPage + 1];
        [self setPageCombobox:currentPage+1];
    }
}

///event when click previous page
- (IBAction)previousPage:(id)sender {
    int currentPage = [_pageController currentPage];
    if(currentPage - 1 >= 0)
    {
        [_pageController setCurrentPage:currentPage - 1];
        [self setPageCombobox:currentPage -1 ];
    }
}

///event when click begin page
- (IBAction)beginPage:(id)sender {
    NSPoint newScrollOrigin;
    
    // assume that the scrollview is an existing variable
    if ([[_listPage documentView] isFlipped]) {
        newScrollOrigin=NSMakePoint(0.0,0.0);
    } else {
        newScrollOrigin=NSMakePoint(0.0,NSMaxY([[_listPage documentView] frame])
                                    -NSHeight([[_listPage contentView] bounds]));
    }
    [[_listPage documentView] scrollPoint:newScrollOrigin];
    [self setPageCombobox:0];
}
///event when click end page
- (IBAction)endPage:(id)sender {
    [_pageController setCurrentPage:totalPage];
    [self setPageCombobox:totalPage - 1];
}

///event when click zoom out page button
- (IBAction)zoomOut:(id)sender {
    if(_currentZoom < 19)
    {
        _currentZoom++;
        [_comboZoom selectItemAtIndex:(_currentZoom + 1)];
        [_sliderZoom setIntValue:_currentZoom];
    }
}


///event when click zoon in page button
- (IBAction)zoomIn:(id)sender {
    if (_currentZoom > 1) {
        _currentZoom--;
        [_comboZoom selectItemAtIndex:(_currentZoom+1)];
        [_sliderZoom setIntValue:_currentZoom];
    }
}

///slider moved
- (IBAction)sliderMoved:(id)sender {
    int zoomlevel = [_sliderZoom intValue];
    [_comboZoom selectItemAtIndex:(zoomlevel+1)];
}

///event when click thumbnails page
- (IBAction)outLineThumbnailSelected:(id)sender {
    long clickedSegment = [sender selectedSegment];
    if(clickedSegment == 0)
    {
        //outline
        if([_outLineParent isHidden])
        {
            [_outLineParent setHidden:NO];
        }
        if(_thumbnail)
        {
            [_thumbnail showHideThumbnails:YES];
        }
        if(![_searchTableView isHidden])
        {
            [_searchTableView setHidden:YES];
        }
    }else
    {
        if(![_outLineParent isHidden])
        {
            [_outLineParent setHidden:YES];
        }
        if(![_searchTableView isHidden])
        {
            [_searchTableView setHidden:YES];
        }
        //thumbnail
        if(_thumbnail)
        {
            [_thumbnail showHideThumbnails:NO];
        }
    }
}


///event when resize thumbnails
-(void) splitViewDidResizeSubviews:(NSNotification *)notification
{
    if(_thumbnail)
    {
        fz_rect bounds;
        int total = fz_count_pages(doc);
        int numberPage =  0;
        if(total > 1)
            numberPage = 1;
        page = fz_load_page(doc, numberPage);
        fz_bound_page(doc, page, &bounds);
        int width = bounds.x1 - bounds.x0;
        int height = bounds.y1 - bounds.y0;
        NSRect size  = [_leftControl frame];
        float scale = width/size.size.width;
        height = (int) height/scale;
        width = size.size.width;
        [_thumbnail setWithPage:width];
        [_thumbnail setHeightPage:height];
    }
}

///size max thumbnail
-(CGFloat) splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMaximumPosition ofSubviewAt:(NSInteger)dividerIndex
{
    return 350;
}

///size min thumbnail
-(CGFloat) splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMinimumPosition ofSubviewAt:(NSInteger)dividerIndex{
    return 250;
}

///resize subview when resize parentview
-(void) splitView:(NSSplitView *)splitView resizeSubviewsWithOldSize:(NSSize)oldSize
{
    float dividerThickness = [splitView dividerThickness];
    id sv1 = [[splitView subviews] objectAtIndex:0];
    id sv2 = [[splitView subviews] objectAtIndex:1];
    NSRect leftFrame  = [sv1 frame];
    NSRect rightFrame = [sv2 frame];
    NSRect newFrame  = [splitView frame];
    
    if (splitView != _splitView) return;
    
    leftFrame.size.height = newFrame.size.height;
    leftFrame.origin = NSMakePoint(0,0);
    rightFrame.size.width = newFrame.size.width - leftFrame.size.width
    - dividerThickness;
    rightFrame.size.height = newFrame.size.height;
    rightFrame.origin.x = leftFrame.size.width + dividerThickness;
    
    [sv1 setFrame:leftFrame];
    [sv2 setFrame:rightFrame];
}


///outline selected event
-(void) outlineViewSelectionDidChange:(NSNotification *)notification
{
    if ([_outLineView selectedRow] != -1) {
        OutlineItem *item = [_outLineView itemAtRow:[_outLineView selectedRow]];
        int numberPage = [[item page] intValue];
        if(numberPage - 1 < totalPage && numberPage > 0)
        {
            [_pageController setCurrentPage:numberPage];
            [self setPageCombobox:numberPage - 1];
        }
    }
}

///scroll page when click thumbnail
-(void)selectPage:(int)numberPage
{
    if (numberPage >= 0 && numberPage <totalPage) {
        if (numberPage != currentThumbnail) {
            currentThumbnail = numberPage;
            [_pageController setCurrentPage:numberPage];
            [self setPageCombobox:numberPage];
        }
    }
}

///select page from combobox
-(void)comboBoxSelectionDidChange:(NSNotification *)notification
{
    NSComboBox *comboBox = (NSComboBox *)[notification object];
    if (comboBox ==_comboPage && _selectCombo == NO) {
        int numberPage = (int)[_comboPage indexOfSelectedItem];
        if (numberPage >= 0 && numberPage <totalPage) {
            int heightPage = [_pageController heightPage] * (numberPage);
            NSPoint newScrollOrigin =NSMakePoint(0.0,heightPage);
            [_pageController setCurrentPage:numberPage];
            [[_listPage documentView] scrollPoint:newScrollOrigin];
        }
    }
    if (comboBox == _comboZoom) {
        int zoomlevel = (int)[_comboZoom indexOfSelectedItem];
        [_sliderZoom setIntValue:zoomlevel-1];
        _currentZoom = zoomlevel -1;
        int _number =  0;
        if(totalPage > 1)
            _number = 1;
        if(doc)
        {
            fz_rect bounds;
            page = fz_load_page(doc, _number);
            fz_bound_page(doc, page, &bounds);
            int width = bounds.x1 - bounds.x0;
            int height = bounds.y1 - bounds.y0;
            float widthReal = 1000.0;
            int zoom = zoomlevel -1;
            if(zoomlevel == 0)
            {
                NSRect sizeRight = [_rightControl frame];
                widthReal = sizeRight.size.width - 20;
            }
            else if(zoomlevel == 1)
            {
                NSRect sizeRight = [_rightControl frame];
                widthReal = sizeRight.size.height/height * width - 10;
            }
            if(zoom == 8)
            {
                widthReal =widthReal*100/100;
            }else if(zoom ==1){
                widthReal =widthReal*8.33/100;
            }else if(zoom ==2){
                widthReal =widthReal*12.5/100;
            }else if(zoom ==3){
                widthReal =widthReal*25/100;
            }else if(zoom ==4){
                widthReal =widthReal*33.33/100;
            }else if(zoom ==5){
                widthReal =widthReal*50/100;
            }else if(zoom ==6){
                widthReal =widthReal*66.67/100;
            }else if(zoom ==7){
                widthReal =widthReal*75/100;
            }else if(zoom ==9){
                widthReal =widthReal*125/100;
            }else if(zoom ==10){
                widthReal =widthReal*150/100;
            }else if(zoom ==11){
                widthReal =widthReal*200/100;
            }else if(zoom ==12){
                widthReal =widthReal*300/100;
            }else if(zoom ==13){
                widthReal =widthReal*400/100;
            }else if(zoom ==14){
                widthReal =widthReal*600/100;
            }else if(zoom ==15){
                widthReal =widthReal*800/100;
            }else if(zoom ==16){
                widthReal =widthReal*1200/100;
            }else if(zoom ==17){
                widthReal =widthReal*1600/100;
            }else if(zoom ==18){
                widthReal =widthReal*3200/100;
            }else if(zoom ==19){
                widthReal =widthReal*6400/100;
            }
            float scale = widthReal/width;
            float heightReal = height*scale;
            if (_pageController) {
                if ([_rightControl frame].size.width >= widthReal || zoom == 8) {
                    [_pageController setIsZoom:NO];
                }else{
                    [_pageController setIsZoom:YES];
                }
                [_pageController changeWidthHeight:((int)widthReal + 10) height:((int)heightReal + 10)];
                [_listPage setWidthRow:widthReal + 10];
                [_listPage setHeightRow:heightReal + 10];
                [_listPage reloadData];
            }
        }
    }
}

///set page combobox when scroll page
-(void)setPageCombobox:(int)numberPage
{
    [_comboPage selectItemAtIndex:numberPage];
}

///event when scroll page
-(void) scrollPage:(int)numberPage
{
    _selectCombo = YES;
     [_pageController setCurrentPage:numberPage];
    [self setPageCombobox:numberPage];
    _selectCombo = NO;
}

///search delegate



-(BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector {
    BOOL result = NO;
    if (commandSelector == @selector(insertNewline:)) {
		// enter pressed
        [self startThreadSearch];
    }
    return result;
}

-(void) startThreadSearch
{
    [_segmentOutLineThumb setSelected:NO forSegment:0];
    [_segmentOutLineThumb setSelected:NO forSegment:1];
    
    if([_outLineParent isHidden])
    {
        [_outLineParent setHidden:YES];
    }
    if(_thumbnail)
    {
        [_thumbnail showHideThumbnails:YES];
    }
    if([_searchTableView isHidden])
    {
        [_searchTableView setHidden:NO];
    }
    if ([_textSearch isEqualToString:[_searchField stringValue]]) {
        
    }else
    {
        _textSearch =[_searchField stringValue];
        _dataSearch = [[NSMutableDictionary alloc] init];
        _searchController = [[SearchController alloc] init];
        char *needle;
        needle = strdup([[_searchField stringValue] UTF8String]);
        if (strlen(needle) > 0) {
            [_progressSearch startAnimation:self];
            for (int i = 0; i< totalPage;i++) {
                int n = search_page(doc, i, needle, NULL);
                if(n==1)
                {
                    NSString *pageNumber = [NSString stringWithFormat:@"%d",(i+1)];
                    NSString *title = [NSString stringWithFormat:@"Page %d have %d result found",(i+1),n];
                    SearchObject *temp = [[SearchObject alloc] initWithTitle:title page:pageNumber];
                    [temp setNumberPage:(i+1)];
                    [temp setNumberSearch:n];
                    HitView *hitView = [[HitView alloc] initWithSearchResults:temp.numberSearch forDocument:doc];
                    [_dataSearch setObject:hitView
                                    forKey:[NSNumber numberWithInt:(i+1)]];
                    [_searchController addObjectSearch:temp];
                }else if(n> 1)
                {
                    NSString *pageNumber = [NSString stringWithFormat:@"%d",(i+1)];
                    NSString *title = [NSString stringWithFormat:@"Page %d have %d results found",(i+1),n];
                    SearchObject *temp = [[SearchObject alloc] initWithTitle:title page:pageNumber];
                    [temp setNumberPage:(i+1)];
                    [temp setNumberSearch:n];
                    HitView *hitView = [[HitView alloc] initWithSearchResults:temp.numberSearch forDocument:doc];
                    [_dataSearch setObject:hitView
                                    forKey:[NSNumber numberWithInt:(i+1)]];
                    [_searchController addObjectSearch:temp];
                }
            }
            if([_dataSearch count] > 0)
            {
                [_segmentSearch setEnabled:YES];
            }
            [_pageController setSearchData:_dataSearch];
            [_pageController setSearchDataForCell:_dataSearch];
            [_searchTable setDataSource:_searchController];
            [_searchTable reloadData];
            [_progressSearch stopAnimation:self];
        }else
        {
            NSRunAlertPanel(@"Error!", @"Text search is empty!", @"OK", @"Cancel", nil);
        }
    }
}

-(void)controlTextDidChange:(NSNotification *)obj
{
    if ([[_searchField stringValue] isEqualToString:@""]) {
        [_searchField setStringValue:@""];
        if(_searchController)
        {
            [_searchController resetData];
        }
        if(_dataSearch)
        {
            [_dataSearch release];
            _dataSearch = nil;
        }
        if(_pageController)
        {
            [_pageController removeDataSearch];
        }
        [_pageController setSearchDataForCell:nil];
        [_searchTable reloadData];
        [_segmentSearch setEnabled:NO];
        [_segmentSearch setEnabled:YES forSegment:0];
        [_segmentSearch setEnabled:YES forSegment:1];
        _textSearch = nil;
    }else
    {
        return;
    }
}

#pragma endEvent

#pragma tableview search
-(void) tableViewSelectionDidChange:(NSNotification *)notification
{
    NSTableView *table = (NSTableView *)[notification object];
    if (table == _searchTable) {
        NSInteger selected = [_searchTable selectedRow];
        if(selected ==0)
        {
            [_segmentSearch setEnabled:NO forSegment:0];
            [_segmentSearch setEnabled:YES forSegment:1];
        }else if(selected == [_searchTable numberOfRows] -1)
        {
            [_segmentSearch setEnabled:NO forSegment:1];
            [_segmentSearch setEnabled:YES forSegment:0];
        }else if(selected > 0)
        {
            [_segmentSearch setEnabled:YES forSegment:0];
            [_segmentSearch setEnabled:YES forSegment:1];
        }
        // Get row at specified index
        if(_searchController)
        {
            SearchObject *object = [_searchController getObjectAtIndex:selected];
            int numberPage = [object numberPage];
            if (_pageController) {
                [_pageController setCurrentPage:numberPage -1];
                [self setPageCombobox:numberPage -1];
            }
        }
    }
}

///event when click segment thumbnails or outlines
- (IBAction)segmentedSearchClicked:(id)sender {
    long clickedSegment = [sender selectedSegment];
    if(clickedSegment == 0)
    {
        NSInteger selected = [_searchTable selectedRow];
        if (selected > 0) {
            selected -=1;
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:selected];
            [_searchTable selectRowIndexes:indexSet byExtendingSelection:NO];
            if(selected == 0)
            {
                [_segmentSearch setEnabled:NO forSegment:0];
            }
            if(selected < [_searchTable numberOfRows])
            {
                [_segmentSearch setEnabled:YES forSegment:1];
            }
        }
    }else
    {
        NSInteger selected = [_searchTable selectedRow];
        if (selected < [_searchTable numberOfRows]) {
            selected +=1;
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:selected];
            [_searchTable selectRowIndexes:indexSet byExtendingSelection:NO];
            if(selected == ([_searchTable numberOfRows] -1))
            {
                [_segmentSearch setEnabled:NO forSegment:1];
            }
            if(selected > 0)
            {
                [_segmentSearch setEnabled:YES forSegment:0];
            }
        }
    }
    
}

-(void)clearTextSearch
{
    [_searchField setStringValue:@""];
    if(_searchController)
    {
        [_searchController resetData];
    }
    if(_dataSearch)
    {
        [_dataSearch release];
        _dataSearch = nil;
    }
    if(_pageController)
    {
        [_pageController removeDataSearch];
    }
    [_pageController setSearchDataForCell:nil];
    [_searchTable reloadData];
    [_segmentSearch setEnabled:NO];
    [_segmentSearch setEnabled:YES forSegment:0];
    [_segmentSearch setEnabled:YES forSegment:1];
    _textSearch = nil;
}
- (IBAction)printing:(id)sender {
    NSPrintInfo *printInfo;
    NSPrintOperation *printOp;
    printInfo = [NSPrintInfo sharedPrintInfo];
    [printInfo setHorizontalPagination: NSFitPagination];
    [printInfo setVerticalPagination: NSFitPagination];
    [printInfo setVerticallyCentered:YES];
    [printInfo setHorizontallyCentered:YES];
    NSSize size = [printInfo paperSize];
    CoolView *view = [[[CoolView alloc]initWithDocRef:NSMakeRect(0, 0, size.width, size.height) doc:docRef] autorelease];
    printOp = [NSPrintOperation printOperationWithView:view printInfo:printInfo];
    [printOp runOperation];

}

#pragma end tableview search
- (IBAction)handToolBar:(id)sender {
      [_pageController addTextSelectForCell:NO];
}
- (IBAction)selectToolBar:(id)sender {
    [_pageController addTextSelectForCell:YES];
}
- (IBAction)note:(id)sender {
    [_pageController addDrawHand:YES];
}

- (IBAction)settingToolBar:(id)sender {
    long index = [sender indexOfSelectedItem];
    if (index == 1) {
        _typeSettingColor = 1;
    }else if (index ==2)
    {
        _typeSettingColor = 2;
    }else if (index == 3)
    {
        _typeSettingColor = 3;
    }else if (index == 4)
    {
        _typeSettingColor = 4;
    }
    NSColorPanel* cp = [NSColorPanel sharedColorPanel];
    [cp setDelegate:self];
    [cp setTarget:self];
    
    if (_typeSettingColor ==1) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        if([ud boolForKey:@"ColorHighLight"])
        {
            int colorHightLignt = (int) [[NSUserDefaults standardUserDefaults] integerForKey:@"ColorHighLight"];
            NSColor *colorhight = colorDecode(colorHightLignt);
            [cp setColor:colorhight];
        }
        else
        {
            [cp setColor:[NSColor blueColor]];
        }
    }
    else if (_typeSettingColor ==2) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        if([ud boolForKey:@"ColorUnderLine"])
        {
            int colorHightLignt = (int) [[NSUserDefaults standardUserDefaults] integerForKey:@"ColorUnderLine"];
            NSColor *colorhight = colorDecode(colorHightLignt);
            [cp setColor:colorhight];
        }
        else
        {
            [cp setColor:[NSColor blueColor]];
        }
    }else if(_typeSettingColor ==3)
    {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        if([ud boolForKey:@"ColorStrikeOut"])
        {
            int colorHightLignt = (int) [[NSUserDefaults standardUserDefaults] integerForKey:@"ColorStrikeOut"];
            NSColor *colorhight = colorDecode(colorHightLignt);
            [cp setColor:colorhight];
        }
        else
        {
            [cp setColor:[NSColor blueColor]];
        }
    }else if (_typeSettingColor == 4)
    {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        if([ud boolForKey:@"ColorDraw"])
        {
            int colorHightLignt = (int) [[NSUserDefaults standardUserDefaults] integerForKey:@"ColorDraw"];
            NSColor *colorhight = colorDecode(colorHightLignt);
            [cp setColor:colorhight];
        }
        else
        {
            [cp setColor:[NSColor blueColor]];
        }
    }
    [cp setAction:@selector(changeColor:)];
    [cp setContinuous:YES];
    [NSApp runModalForWindow:cp];
    [cp orderOut:cp];
}

-(void)changeColor:(NSColorPanel*)colorPanel{
    _colorSetting = colorPanel.color;
    NSLog(@"sdcds");
}

- (IBAction)saveDocument:(id)sender {
    
    pdf_document *idoc = pdf_specifics(doc);
	if (idoc && pdf_has_unsaved_changes(idoc))
	{
        
        NSAlert *alert = [[NSAlert alloc] init];
        [alert addButtonWithTitle:@"Save Document"];
        [alert addButtonWithTitle:@"Cancel"];
        [alert setMessageText:@"Save Document?"];
        [alert setInformativeText:@"Changes have been made to the document that will be lost if not saved"];
        [alert setAlertStyle:NSWarningAlertStyle];
        if ([alert runModal] == NSAlertFirstButtonReturn) {
            // OK clicked, delete the record
            saveDoc(_filePath,doc);
        }else
        {
            NSLog(@"Cancle");
        }
        [alert release];
    }
}


- (void) dealloc
{
    [docRef release]; docRef = nil; doc = NULL;
    [_outLineView release]; _outLineView = nil;
    [_outLineParent release]; _outLineParent = nil;
    [_searchTableView release];_searchTableView = nil;
    [_searchTable release]; _searchTable = nil;
    [_listView release]; _listView = nil;
    [_listPage release]; _listPage = nil;
    [_segmentOutLineThumb release]; _segmentOutLineThumb = nil;
    [_segmentSearch release]; _segmentSearch = nil;
    [_thumbnail release]; _thumbnail = nil;
    [_pageController release]; _pageController = nil;
    [_comboPageController release]; _comboPageController = nil;
    [_comboZoomController release]; _comboZoomController = nil;
    [_splitView release]; _splitView = nil;
    [_leftControl release]; _leftControl = nil;
    [_rightControl release]; _rightControl = nil;
    [_comboPage release]; _comboPage = nil;
    [_comboZoom release]; _comboZoom = nil;
    [_sliderZoom release]; _sliderZoom = nil;
    [window release]; window = nil;
    [_searchField release]; _searchField = nil;
    [_searchController release]; _searchController = nil;
    [_dataSearch release]; _dataSearch = nil;
    [_progressSearch release];_progressSearch = nil;
    [_textSearch release]; _textSearch = nil;
    [_toolbar release]; _toolbar = nil;
    [_colorSetting release]; _colorSetting = nil;
    [super dealloc];
}
@end
